package db

import (
	"gitee.com/DonHz/cloud-file-storage/db/mydb"
	"gitee.com/DonHz/cloud-file-storage/model"
	"time"
)

type UserFile struct {
	UserName    string
	FileHash    string
	FileName    string
	FileSize    int64
	UploadAt    string
	LastUpdated string
}

func OnUserFileUploadFinished(username, filehash, filename string, filesize int64) bool {
	now := time.Now()
	res := mydb.DB.Create(&model.UserFile{
		UserName: username,
		FileHash: filehash,
		FileName: filename,
		FileSize: filesize,
		UploadAt: now.Format("2006-01-02 15:04:05"),
		UpdateAt: now.Format("2006-01-02 15:04:05"),
	})
	if res.Error != nil {
		return false
	}
	if res.RowsAffected == 1 {
		return true
	}
	return true
}

func QueryUserFileMetas(username string, limit int) ([]UserFile, error) {
	var userFiles []model.UserFile
	res := mydb.DB.Where("user_name = ?", username).Limit(limit).Find(&userFiles)
	if res.Error != nil {
		return nil, res.Error
	}
	ufiles := make([]UserFile, 0)
	for _, v := range userFiles {
		ufiles = append(ufiles, UserFile{
			UserName:    v.UserName,
			FileHash:    v.FileHash,
			FileName:    v.FileName,
			FileSize:    v.FileSize,
			UploadAt:    v.UploadAt,
			LastUpdated: v.UpdateAt,
		})
	}
	return ufiles, nil
}
